$(document).ready(
	function(){ 
		$('#consoleDlg')[0].style.display = "none";
		
		$("#gridTable").jqGrid({   
            url:getContextPath()+"/base/area/getAllAreas.do",   
            datatype: "json",// "local",
            height: 350,   
            colNames:['序号','区域编码','省份', '城市名', '区名','邮编'],
			colModel:[
				{name:'id', index:'id', width:0, align:"left", hidden:true},
		   		{name:'areaID', index:'areaID', width:100, align:"left"},
		   		{name:'province', index:'province', width:150, align:"left"},
		   		{name:'city', index:'city', width:150, align:"left"},
		   		{name:'district', index:'district', width:150, align:"left", sortable:false},
		   		{name:'postCode', index:'postCode', width:150, align:"left", sortable:false} 
			],
            sortname:'id',   
            // sortorder:'asc',
            viewrecords:true, 
            pgtext : "页 {0} 共 {1}页",
            recordtext:'记录 {0} - {1} 总记录数 {2}',  
            emptyrecords : "无数据",
            loadtext : "获取数据中...",
            rowNum: 15,//10,   
            loadonce: true,
            //rowList:[10,20,30],   
            jsonReader: { 
				repeatitems:false,   	 // 设置成false，在后台设置值的时候，可以乱序。且并非每个值都得设
				root: "rows",               // 数据行（默认为：rows）   
				total: "total",        // 总记录数   
				page: "page",            // 当前页   
				records: "records"
                //root:"dataRows",        // 数据行（默认为：rows）
                //page: "pages",    // 当前页
                //total: "totals",  // 总页数
                //records: "records",  // 总记录数
                //repeatitems : false    
            }, 
            //prmNames : {
				//search : "search",
				//rows:"pageModel.rows",
				//page:"pageModel.page",
				// sort:"page.orderBy",
				// order:"page.order"
			//}, 
            pager:"#gridPager",  
            caption: "区域信息 "
		});  
		$("#gridTable").jqGrid('navGrid','#gridPager',{edit:false,add:false,del:false});
		/**
		var mydata = [
		 {id:"61",name:"123阿61",areaID:"areaID61",province:"province",city:"city",district:"district",postCode:"postCode"},
		 {id:"2",name:"123阿",areaID:"areaID",province:"province",city:"city",district:"district",postCode:"postCode"},
		 {id:"3",name:"123阿",areaID:"areaID",province:"province",city:"city",district:"district",postCode:"postCode"},
		 {id:"4",name:"123阿",areaID:"areaID",province:"province",city:"city",district:"district",postCode:"postCode"},
		 {id:"5",name:"123阿",areaID:"areaID",province:"province",city:"city",district:"district",postCode:"postCode"},
		 {id:"6",name:"123阿",areaID:"areaID",province:"province",city:"city",district:"district",postCode:"postCode"},
		 {id:"7",name:"123阿",areaID:"areaID",province:"province",city:"city",district:"district",postCode:"postCode"},
		 {id:"8",name:"123阿",areaID:"areaID",province:"province",city:"city",district:"district",postCode:"postCode"},
		 {id:"9",name:"123阿",areaID:"areaID",province:"province",city:"city",district:"district",postCode:"postCode"},
		 {id:"10",name:"123阿",areaID:"areaID",province:"province",city:"city",district:"district",postCode:"postCode"},
		 {id:"11",name:"123阿",areaID:"areaID",province:"province",city:"city",district:"district",postCode:"postCode"},
		 {id:"12",name:"123阿",areaID:"areaID",province:"province",city:"city",district:"district",postCode:"postCode"},
		 {id:"13",name:"123阿",areaID:"areaID",province:"province",city:"city",district:"district",postCode:"postCode"},
		 {id:"14",name:"123阿",areaID:"areaID",province:"province",city:"city",district:"district",postCode:"postCode"},
		 {id:"15",name:"123阿",areaID:"areaID",province:"province",city:"city",district:"district",postCode:"postCode"},
		 {id:"16",name:"123阿",areaID:"areaID",province:"province",city:"city",district:"district",postCode:"postCode"},
		 {id:"17",name:"123阿",areaID:"areaID",province:"province",city:"city",district:"district",postCode:"postCode"},
		 {id:"18",name:"123阿",areaID:"areaID",province:"province",city:"city",district:"district",postCode:"postCode"},
		 {id:"19",name:"123阿",areaID:"areaID",province:"province",city:"city",district:"district",postCode:"postCode"},
		 {id:"20",name:"123阿",areaID:"areaID",province:"province",city:"city",district:"district",postCode:"postCode"},
		 {id:"21",name:"123阿",areaID:"areaID",province:"province",city:"city",district:"district",postCode:"postCode"},
		 {id:"22",name:"123阿",areaID:"areaID",province:"province",city:"city",district:"district",postCode:"postCode"},
		 {id:"23",name:"123阿",areaID:"areaID",province:"province",city:"city",district:"district",postCode:"postCode"} ];
		 for(var i=0;i<=mydata.length;i++)
			 jQuery("#gridTable").jqGrid('addRowData',i+1,mydata[i]); 
		$("#gridTable").trigger("reloadGrid");
		**/
		
		// 配置对话框
		$("#consoleDlg").dialog( {
			autoOpen : false,
			modal : true, // 设置对话框为模态（modal）对话框
			resizable : true,
			width : 480,
			buttons : { // 为对话框添加按钮
				"取消" : function() {
					$("#consoleDlg").dialog("close")
				},
				"添加" : addAreaInfo,
				"保存" : updateAreaInfo,
				"删除" : deleteAreaInfo
			}
		});  
	}
)

		// getContextPath
		function getContextPath() {
    		var pathName = document.location.pathname;
    		var index = pathName.substr(1).indexOf("/");
    		var result = pathName.substr(0,index+1);
    		return result;
		};

	var openDialog4Adding = function() {  
		var consoleDlg = $("#consoleDlg");  
		var dialogButtonPanel = consoleDlg.siblings(".ui-dialog-buttonpane");  
		consoleDlg.find("input").removeAttr("disabled").val("");  
		dialogButtonPanel.find("button:not(:contains('取消'))").hide();  
		dialogButtonPanel.find("button:contains('添加')").show();  
		consoleDlg.dialog("option", "title", "添加区域信息 ").dialog("open");  
	};  
	
	var openDialog4Updating = function() {
		var consoleDlg = $("#consoleDlg");  
        var dialogButtonPanel = consoleDlg.siblings(".ui-dialog-buttonpane");    
        consoleDlg.find("input").removeAttr("disabled");  
        dialogButtonPanel.find("button:not(:contains('取消'))").hide();  
        dialogButtonPanel.find("button:contains('保存')").show();  
        consoleDlg.dialog("option", "title", "修改区域信息");  
          
        loadSelectedRowData();  
	};
	
	var openDialog4Deleting = function() {
		var consoleDlg = $("#consoleDlg");  
        var dialogButtonPanel = consoleDlg.siblings(".ui-dialog-buttonpane");         
        consoleDlg.find("input").attr("disabled", true);  
        dialogButtonPanel.find("button:not(:contains('取消'))").hide();  
        dialogButtonPanel.find("button:contains('删除')").show();  
        consoleDlg.dialog("option", "title", "删除区域");  
          
        loadSelectedRowData();  
	};
	
    var loadSelectedRowData = function() {
    	var selectedRowId = $("#gridTable").jqGrid("getGridParam", "selrow");
    	//alert("selectRowID:"+selectedRowId);
    	if (!selectedRowId) {
    		alert("请先选择需要编辑的行!");
    		return false;
    	} else {
    		var params = {"eid" : selectedRowId};
    		// 从Server读取对应ID的JSON数据
    		$.ajax( {
    			type:"POST",   
    			url : getContextPath()+"/base/area/getAreaByID.do",
    			data : params,
    			dataType : "json",
    			//contentType: "application/json",
    			cache : false,
    			async:false,
    			error : function(textStatus, errorThrown) {
					alert("系统ajax交互错误: " + textStatus.responseText);
				},
				success : function(data, textStatus) {
					// 如果读取结果成功，则将信息载入到对话框中     
					var rowData = data;
					var consoleDlg = $("#consoleDlg");

					consoleDlg.find("#selectId").val(rowData.id);
					//alert("hiddenID1:"+consoleDlg.find("#selectId").val());
					consoleDlg.find("#eAreaID").val(rowData.areaID);
					consoleDlg.find("#eProvince").val(rowData.province);
					consoleDlg.find("#eCity").val(rowData.city);
					consoleDlg.find("#eDistrict").val(rowData.district);
					consoleDlg.find("#ePostCode").val(rowData.postCode);
					// 根据新载入的数据将表格中的对应数据行一并更新一下
					var dataRow = {
							id : rowData.id, // 从Server端得到系统分配的id  
							areaID : rowData.areaID,
							province : rowData.province,
							city : rowData.city,
							district : rowData.district,
							postCode : rowData.postCode
					};

					$("#gridTable").jqGrid("setRowData", data.id, dataRow);

					// 打开对话框
					consoleDlg.dialog("open");
				}
    		});
    	}
    };    
	
    var checkValid = function() {
    	var consoleDlg = $("#consoleDlg");
    	var eAreaID = $.trim(consoleDlg.find("#eAreaID").val()); 	
    	if (eAreaID=="") {
    		alert("'区域代码'为必填信息");
    		return false;
    	}
    	var eProvince = $.trim(consoleDlg.find("#eProvince").val());
		if (eProvince=="") {
    		alert("'省份'为必填信息");
    		return false;
    	}
		var eCity = $.trim(consoleDlg.find("#eCity").val());
		if (eCity=="") {
    		alert("'城市名'为必填信息");
    		return false;
    	}
    }
    
	var addAreaInfo = function() {
		var consoleDlg = $("#consoleDlg");

		if (checkValid()==false) return false;
		
		var eAreaID = $.trim(consoleDlg.find("#eAreaID").val());
		var eProvince = $.trim(consoleDlg.find("#eProvince").val());
		var eCity = $.trim(consoleDlg.find("#eCity").val());
		var eDistrict = $.trim(consoleDlg.find("#eDistrict").val());
		var ePostCode = $.trim(consoleDlg.find("#ePostCode").val());

		/**
		var params = {
				"eAreaID" : eAreaID,
				"eProvince" : eProvince,
				"eCity" : eCity,
				"eDistrict" : eDistrict,
				"ePostCode" : ePostCode
		};
		**/
		//以下方式，通过form的序列化，得到prop=value&&prop=value格式的requestData，也可行
		params = $("#consoleForm").serialize();

		var actionUrl = getContextPath()+"/base/area/addArea.do";

		$.ajax( {
				type: "POST",
				url : actionUrl,
				data : params,
				dataType : "json",
				cache : false,
				error : function(textStatus, errorThrown) {
					alert("系统ajax交互错误: " + textStatus);
				},
				success : function(data, textStatus) {
					if (data != null) {
						var dataRow = {
							id : data.id, // 从Server端得到系统分配的id  
							areaID : data.areaID,
							province : data.province,
							city : data.city,
							district : data.district,
							postCode : data.postCode
						};

						var srcrowid = $("#gridTable").jqGrid("getGridParam",
								"selrow");

						if (srcrowid) {
							$("#gridTable").jqGrid("addRowData",
									data.id, dataRow, "before",
									srcrowid);

						} else {
							$("#gridTable").jqGrid("addRowData",
									data.id, dataRow, "first");
						}
						consoleDlg.dialog("close");

						alert("区域信息添加操作成功!");

					} else {
						alert("区域代码重复，添加操作失败!");
					}
				}
			});  
	};
	
	var updateAreaInfo = function() {
		var consoleDlg = $("#consoleDlg");

		if (checkValid()==false) return false;
		//alert("hiddenID2:"+consoleDlg.find("#selectId").val());
		var eID = $.trim(consoleDlg.find("#selectId").val());  
		var eAreaID = $.trim(consoleDlg.find("#eAreaID").val());
		var eProvince = $.trim(consoleDlg.find("#eProvince").val());
		var eCity = $.trim(consoleDlg.find("#eCity").val());
		var eDistrict = $.trim(consoleDlg.find("#eDistrict").val());
		var ePostCode = $.trim(consoleDlg.find("#ePostCode").val());
		var params = {
				"eID" : eID,
				"eAreaID" : eAreaID,
				"eProvince" : eProvince,
				"eCity" : eCity,
				"eDistrict" : eDistrict,
				"ePostCode" : ePostCode
		};
		var actionUrl = getContextPath() + "/base/area/updateArea.do";
		$.ajax( {
			type : "POST",
			url : actionUrl,
			data : params,
			dataType : "json",
			cache : false,
			error : function(textStatus, errorThrown) {
				alert("系统ajax交互错误: " + textStatus);
			},
			success : function(data, textStatus) {
				if (data != null) {
					var dataRow = {
							id : data.id, // 从Server端得到系统分配的id  
							areaID : data.areaID,
							province : data.province,
							city : data.city,
							district : data.district,
							postCode : data.postCode
					};
					alert("区域信息更新成功!");
					consoleDlg.dialog("close");
					$("#gridTable").jqGrid("setRowData", data.id, dataRow);
				} else {
					alert("区域代码重复，修改操作失败!");
				}
			}
		});
	};
	
	var deleteAreaInfo = function() {
		var consoleDlg = $("#consoleDlg");  
		
		var r=confirm("确认要删除该信息吗？");
		if (r==false) {
			consoleDlg.dialog("close"); 
			return false;
		}
        
        var pId = $.trim(consoleDlg.find("#selectId").val());  
        var params = {"eID" : pId};  
        var actionUrl = getContextPath() + "/base/area/deleteArea.do";
        $.ajax({  
        	type : "POST",
            url : actionUrl,  
            data : params,  
            //dataType : "json",  
            cache : false,  
            error : function(textStatus, errorThrown) {  
                alert("系统ajax交互错误: " + textStatus);  
            },  
            success : function(data, textStatus) {  
                if (data == "success") {  
                    $("#gridTable").jqGrid("delRowData", pId);  
                    consoleDlg.dialog("close");  
                    alert("区域信息删除成功!");  
                } else {  
                    alert("删除操作失败!");  
                }  
            }  
        });  
	};
